package service

import (
	"fmt"
	"ginorm/models"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 新增用户
func CreateUser(c *gin.Context) {
	user := models.UserInfo{}

	err := c.ShouldBindJSON(&user)
	if err != nil {
		fmt.Println(err)
	}

	if user.Username == "" && user.Password == "" {
		c.JSON(-1, gin.H{
			"message": "账号或密码不能为空",
		})
		return
	} else {
		phoneIsExist := models.FindUsername(user.Username)
		if phoneIsExist.Username != "" {
			c.JSON(-1, gin.H{
				"message": "用户名已注册",
			})
			return
		} else {
			models.CreateUser(&user)
			c.JSON(200, gin.H{
				"message": "创建用户成功",
				"data":    user,
			})
		}
	}

}

// 删除用户
func DeleteUser(c *gin.Context) {
	user := models.UserInfo{}
	id, _ := strconv.Atoi(c.Query("id"))
	user.ID = uint(id)

	models.DeleteUser(&user)
	c.JSON(200, gin.H{
		"message":  "删除成功",
		"id":       user.ID,
		"username": user.Username,
	})

}

// 修改密码
func UpdatePassword(c *gin.Context) {
	user := models.UserInfo{}
	id, _ := strconv.Atoi(c.PostForm("id"))
	user.ID = uint(id)
	user.Password = c.PostForm("password")

	models.UpdateUser(&user)
	c.JSON(200, gin.H{
		"message": "修改密码成功",
	})
}

// 查询所有用户
func SelectUser(c *gin.Context) {
	user := models.SelectUser()
	c.JSON(200, gin.H{
		"message": "查询用户成功",
		"data":    user,
	})
}
